#include "goose61850publisher.h"

Goose61850Publisher::Goose61850Publisher()
{
    m_interface = "lo";

//    printf("Using interface %s\n", m_interface.toLatin1().data());

    m_dataSetValues = LinkedList_create();

    LinkedList_add(m_dataSetValues, MmsValue_newIntegerFromInt32(1234));
    LinkedList_add(m_dataSetValues, MmsValue_newBinaryTime(false));
    LinkedList_add(m_dataSetValues, MmsValue_newIntegerFromInt32(5678));

    m_gooseCommParameters.appId = 1000;
    m_gooseCommParameters.dstAddress[0] = 0x01;
    m_gooseCommParameters.dstAddress[1] = 0x0c;
    m_gooseCommParameters.dstAddress[2] = 0xcd;
    m_gooseCommParameters.dstAddress[3] = 0x01;
    m_gooseCommParameters.dstAddress[4] = 0x00;
    m_gooseCommParameters.dstAddress[5] = 0x01;
    m_gooseCommParameters.vlanId = 0;
    m_gooseCommParameters.vlanPriority = 4;

    m_publisher = GoosePublisher_create(&m_gooseCommParameters, m_interface.toLatin1().data());

    if (m_publisher) {
        GoosePublisher_setGoCbRef(m_publisher, "simpleIOGenericIO/LLN0$GO$gcbAnalogValues");
        GoosePublisher_setConfRev(m_publisher, 1);
        GoosePublisher_setDataSetRef(m_publisher, "simpleIOGenericIO/LLN0$AnalogValues");
        GoosePublisher_setTimeAllowedToLive(m_publisher, 500);
    }
    else{
        exit(-1);
    }
}

Goose61850Publisher::~Goose61850Publisher()
{
    if (m_publisher) GoosePublisher_destroy(m_publisher);
    LinkedList_destroyDeep(m_dataSetValues, (LinkedListValueDeleteFunction) MmsValue_delete);
}

void Goose61850Publisher::setInterface(QString t)
{
    m_interface = t;

    GoosePublisher_destroy(m_publisher);
    m_publisher = GoosePublisher_create(&m_gooseCommParameters, m_interface.toLatin1().data());
    if (m_publisher) {
        GoosePublisher_setGoCbRef(m_publisher, "simpleIOGenericIO/LLN0$GO$gcbAnalogValues");
        GoosePublisher_setConfRev(m_publisher, 1);
        GoosePublisher_setDataSetRef(m_publisher, "simpleIOGenericIO/LLN0$AnalogValues");
        GoosePublisher_setTimeAllowedToLive(m_publisher, 500);
    }
    else{
        exit(-1);
    }
}

void Goose61850Publisher::run()
{

}

void Goose61850Publisher::pubulisher()
{
    if (m_publisher) {

        if (GoosePublisher_publish(m_publisher, m_dataSetValues) == -1)
        {
            qDebug("Error sending message!\n");
        }

    }
    else {
        qDebug("Failed to create GOOSE publisher. Reason can be that the Ethernet interface doesn't exist or root permission are required.\n");
    }

}
